<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElDatePicker, ElMessageBox, ElMessage } from 'element-plus'
import CommonLayout from '@/components/CommonLayout.vue'
import { getSalesOrders, searchSalesOrders, createSalesOrder, updateSalesOrder, deleteSalesOrder, approveSalesOrder, closeSalesOrder } from '@/api/salesOrder'
import apiRequest from '@/utils/apiRequest'
// 正确导入物料API
import materialApi from '@/api/material'

// 销售订单列表数据
const salesOrders = ref([])
// 分页信息
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
// 搜索条件
const searchForm = ref({
  keyword: '',
  customerId: '',
  status: ''
})
// 客户列表
const customers = ref([])
// 物料列表
const materials = ref([])
// 对话框状态
const dialogVisible = ref(false)
const dialogType = ref('create') // 'create' or 'update'
// 表单数据
const formData = ref({
  id: 0,
  orderNumber: '',
  customerId: '',
  orderDate: '',
  deliveryDate: '',
  status: 0, // 0: 待审核, 1: 已审核, 2: 已关闭
  totalAmount: 0,
  remark: '',
  items: []
})

// 状态选项
const statusOptions = [
  { label: '待审核', value: 0 },
  { label: '已审核', value: 1 },
  { label: '已关闭', value: 2 }
]

// 加载销售订单数据
const loadSalesOrders = async () => {
    try {
      console.log('请求销售订单参数:', {
        keyword: searchForm.value.keyword,
        customerId: searchForm.value.customerId,
        status: searchForm.value.status
      })
      const response = await searchSalesOrders(
        searchForm.value.keyword,
        searchForm.value.customerId,
        searchForm.value.status
      )
      console.log('销售订单响应:', response)
      // 处理后端返回的格式 {$id: 1, $values: Array(0)}
      salesOrders.value = response.$values || response.data || []
      total.value = response.totalCount || salesOrders.value.length || 0
    } catch (error) {
      ElMessage.error('获取销售订单数据失败')
      console.error('Failed to load sales orders:', error)
      console.error('错误详情:', error.response ? error.response.data : error.message)
      // 打印详细的验证错误
      if (error.response && error.response.data) {
        console.error('完整错误响应:', JSON.stringify(error.response.data))
        if (error.response.data.errors) {
          console.error('验证错误详情:', JSON.stringify(error.response.data.errors))
        }
      }
    }
  }

// 加载客户数据
const loadCustomers = async () => {
    try {
        // 尝试使用更宽松的参数来获取客户数据
        // 为必需字段提供默认值
        const params = {
          pageIndex: 1,
          pageSize: 100,
          status: '全部',  // 提供默认值
          keyword: 'default',    // 使用有意义的默认值
          customerType: '全部'  // 提供默认值
        }
        console.log('请求客户数据参数:', params)
        // 直接调用apiRequest.get
        console.log('直接调用API前')
        const response = await apiRequest.get('/Customers/search', { params })
        console.log('直接调用API后，响应:', response)
        // 处理后端返回的格式 {$id: 1, $values: Array(0)}
        customers.value = response?.$values || response || []
        // 如果没有客户数据，显示提示
        if (customers.value.length === 0) {
          ElMessage({ message: '没有找到客户数据，请检查筛选条件', type: 'warning' })
        }
      } catch (error) {
        ElMessage.error('获取客户数据失败')
        console.error('Failed to load customers:', error)
        console.error('错误详情:', error.message)
        console.error('错误堆栈:', error.stack)
        console.error('错误配置:', error.config)
        // 尝试获取详细的错误响应数据
        if (error.response) {
          console.error('错误响应状态:', error.response.status)
          console.error('错误响应数据:', JSON.stringify(error.response.data, null, 2))
          // 检查是否有验证错误
          if (error.response.data && error.response.data.errors) {
            console.error('验证错误详情:', JSON.stringify(error.response.data.errors, null, 2))
          }
        } else {
          console.error('完整错误对象:', JSON.stringify(error, null, 2))
        }
      }
  }

// 加载物料数据
const loadMaterials = async () => {
  try {
    const response = await materialApi.getAll()
    materials.value = response.data
  } catch (error) {
    ElMessage.error('获取物料数据失败')
    console.error('Failed to load materials:', error)
  }
}

// 搜索销售订单
const handleSearch = () => {
  currentPage.value = 1
  loadSalesOrders()
}

// 重置搜索表单
const resetForm = () => {
  searchForm.value = {
    keyword: '',
    customerId: '',
    status: ''
  }
  handleSearch()
}

// 打开创建对话框
const openCreateDialog = () => {
  dialogType.value = 'create'
  formData.value = {
    id: 0,
    orderNumber: '',
    customerId: '',
    orderDate: '',
    deliveryDate: '',
    status: 0,
    totalAmount: 0,
    remark: '',
    items: []
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row) => {
  dialogType.value = 'update'
  // 深拷贝行数据到表单
  formData.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    if (dialogType.value === 'create') {
      await createSalesOrder(formData.value)
      ElMessage.success('创建销售订单成功')
    } else {
      await updateSalesOrder(formData.value.id, formData.value)
      ElMessage.success('更新销售订单成功')
    }
    dialogVisible.value = false
    loadSalesOrders()
  } catch (error) {
    ElMessage.error(dialogType.value === 'create' ? '创建销售订单失败' : '更新销售订单失败')
    console.error('Failed to submit form:', error)
  }
}

// 删除销售订单
const confirmDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条销售订单吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteSalesOrder(id)
    ElMessage.success('删除销售订单成功')
    loadSalesOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除销售订单失败')
      console.error('Failed to delete sales order:', error)
    }
  }
}

// 审核销售订单
const handleApprove = async (id) => {
  try {
    // 实际应用中应该获取当前登录用户ID
    const approvedBy = 1
    await approveSalesOrder(id, approvedBy)
    ElMessage.success('审核销售订单成功')
    loadSalesOrders()
  } catch (error) {
    ElMessage.error('审核销售订单失败')
    console.error('Failed to approve sales order:', error)
  }
}

// 关闭销售订单
const handleClose = async (id) => {
  try {
    const reason = await ElMessageBox.prompt('请输入关闭原因', '关闭销售订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    // 实际应用中应该获取当前登录用户ID
    const closedBy = 1
    await closeSalesOrder(id, closedBy, reason.value)
    ElMessage.success('关闭销售订单成功')
    loadSalesOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('关闭销售订单失败')
      console.error('Failed to close sales order:', error)
    }
  }
}

// 添加订单明细
const addOrderItem = () => {
  formData.value.items.push({
    materialId: '',
    quantity: 1,
    unitPrice: 0,
    amount: 0
  })
  calculateTotalAmount()
}

// 删除订单明细
const removeOrderItem = (index) => {
  formData.value.items.splice(index, 1)
  calculateTotalAmount()
}

// 计算订单总金额
const calculateTotalAmount = () => {
  formData.value.totalAmount = formData.value.items.reduce((sum, item) => {
    return sum + (item.quantity * item.unitPrice)
  }, 0)
}

// 监听订单明细变化重新计算总金额
watch(() => formData.value.items, () => {
  calculateTotalAmount()
}, { deep: true })

// 分页变更
const handleSizeChange = (size) => {
  pageSize.value = size
  loadSalesOrders()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  loadSalesOrders()
}

// 初始加载数据
onMounted(() => {
  loadSalesOrders()
  loadCustomers()
  loadMaterials()
})
</script>

<template>
  <CommonLayout title="销售订单管理">
    <template #header-buttons>
      <el-button type="primary" @click="openCreateDialog">
        新增销售订单
      </el-button>
    </template>

    <template #search-form>
      <el-form :model="searchForm" label-width="80px" :inline="true" >
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="订单编号/客户名称"></el-input>
        </el-form-item>
        <el-form-item label="客户">
          <el-select v-model="searchForm.customerId" placeholder="请选择客户">
            <el-option v-for="customer in customers" :key="customer.id" :label="customer.name" :value="customer.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </template>

    <template #data-content>
      <el-table v-loading="salesOrders.length === 0" :data="salesOrders" style="width: 100%">
        <el-table-column prop="orderNumber" label="订单编号" width="180"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="180"></el-table-column>
        <el-table-column prop="orderDate" label="订单日期" width="180"></el-table-column>
        <el-table-column prop="deliveryDate" label="交货日期" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <span v-if="scope.row.status === 0" class="status-pending">待审核</span>
            <span v-else-if="scope.row.status === 1" class="status-approved">已审核</span>
            <span v-else-if="scope.row.status === 2" class="status-closed">已关闭</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单总金额" width="120" align="right"></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status === 0" type="success" size="small" @click="handleApprove(scope.row.id)">审核</el-button>
            <el-button v-if="scope.row.status === 1" type="warning" size="small" @click="handleClose(scope.row.id)">关闭</el-button>
            <el-button type="danger" size="small" @click="confirmDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </template>
  </CommonLayout>

  <!-- 销售订单对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogType === 'create' ? '创建销售订单' : '编辑销售订单'"
    width="70%"
  >
    <el-form :model="formData" label-width="100px">
      <el-form-item label="订单编号" v-if="dialogType === 'update'">
        <el-input v-model="formData.orderNumber" disabled></el-input>
      </el-form-item>
      <el-form-item label="客户" prop="customerId" :rules="[{ required: true, message: '请选择客户', trigger: 'blur' }]">
        <el-select v-model="formData.customerId" placeholder="请选择客户">
          <el-option v-for="customer in customers" :key="customer.id" :label="customer.name" :value="customer.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单日期" prop="orderDate" :rules="[{ required: true, message: '请选择订单日期', trigger: 'blur' }]">
        <el-date-picker v-model="formData.orderDate" type="date" placeholder="请选择订单日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="交货日期" prop="deliveryDate" :rules="[{ required: true, message: '请选择交货日期', trigger: 'blur' }]">
        <el-date-picker v-model="formData.deliveryDate" type="date" placeholder="请选择交货日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" v-if="dialogType === 'update'">
        <el-select v-model="formData.status" disabled placeholder="请选择状态">
          <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息"></el-input>
      </el-form-item>
    </el-form>

    <!-- 订单明细 -->
    <div class="order-items">
      <h4>订单明细</h4>
      <el-button type="primary" size="small" @click="addOrderItem">添加明细</el-button>
      <el-table :data="formData.items" style="width: 100%; margin-top: 10px">
        <el-table-column label="物料" width="200">
          <template #default="scope">
            <el-select v-model="scope.row.materialId" placeholder="请选择物料">
              <el-option v-for="material in materials" :key="material.id" :label="material.name" :value="material.id"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="100">
          <template #default="scope">
            <el-input v-model.number="scope.row.quantity" type="number" min="1"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="100">
          <template #default="scope">
            <el-input v-model.number="scope.row.unitPrice" type="number" min="0"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="100" align="right">
          <template #default="scope">
            {{ (scope.row.quantity * scope.row.unitPrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeOrderItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="total-amount">
      <span>订单总金额：{{ formData.totalAmount.toFixed(2) }}</span>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.status-pending {
  color: #ff9800;
}

.status-approved {
  color: #4caf50;
}

.status-closed {
  color: #f44336;
}

.order-items {
  margin-top: 20px;
}

.total-amount {
  margin-top: 20px;
  text-align: right;
  font-weight: bold;
  font-size: 16px;
}
</style>